package com.bz.xtcx.manager.service.impl;

import com.bz.xtcx.manager.comom.XtcxException;
import com.bz.xtcx.manager.entity.*;
import com.bz.xtcx.manager.enums.CheckStatusEnum;
import com.bz.xtcx.manager.mapper.BusUserCheckMapper;
import com.bz.xtcx.manager.mapper.CmsExchangesEnrollMapper;
import com.bz.xtcx.manager.mapper.CmsExchangesMapper;
import com.bz.xtcx.manager.mapper.CmsFileMapper;
import com.bz.xtcx.manager.persist.conditions.ExchangeEnrollCondition;
import com.bz.xtcx.manager.service.ICmsExchangesService;
import com.bz.xtcx.manager.utils.ExcelUtil;
import com.bz.xtcx.manager.utils.WzDateUtil;
import com.bz.xtcx.manager.vo.VoQueryExchanges;
import com.bz.xtcx.manager.vo.VoResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class CmsExchangesService extends BaseService implements ICmsExchangesService {

    @Autowired
    private CmsExchangesMapper cmsExchangesMapper;
    
    @Autowired
    private CmsExchangesEnrollMapper cmsExchangesEnrollMapper;
    
    @Autowired
    private BusUserCheckMapper busUserCheckMapper;
    
    @Autowired
    private CmsFileMapper cmsFileMapper;
    
    @Override
    public VoResponse saveOrUpdate(CmsExchanges t) {
        VoResponse voRes = new VoResponse();
        int result = 0;
        Date currDate = new Date();
        User user = this.getUser();
        t.setUpdater(user.getUserName());
        //1 定时发布； 0 立刻发布；
        if(t.getPublishNow() == 0) {//立刻发布
            t.setPublishDate(currDate);
        } else if(t.getPublishDate() == null ) {
            voRes.setFail(voRes);
            voRes.setMessage("定时发布时发布时间必选");
            return voRes;
        }
        if(t.getCheckStatus() == CheckStatusEnum.Checked.value()) {
            t.setCheckUserId(user.getUserId());
            t.setCheckDate(currDate);
        }
        this.setCover(t);
        
        if(t.getId() != null) {
//            CmsExchanges old = cmsExchangesMapper.findById(t.getId());
//            if(old.getCheckStatus() == 1 && old.getPublishDate().before(currDate)) {
//                voRes.setFail(voRes);
//                voRes.setMessage("已发布的活动不能进行修改!");
//                return voRes;
//            }
            result = cmsExchangesMapper.update(t);
        }else {
            t.setReadable(1);
            t.setPublishUserId(user.getUserId());
            t.setCreater(user.getUserName());
            result = cmsExchangesMapper.insert(t);
        }
        if(result > 0) {
            List<CmsFile> files = t.getCmsFileList();
            if(files != null && files.size() > 0) {
                for(CmsFile file : files) {
                    if(StringUtils.isEmpty(file.getOwnerId())) {
                        //CmsFile old = cmsFileMapper.findById(file.getId());
                        file.setOwnerId(t.getId());
                        cmsFileMapper.updateOwnerId(file);
                    }
                }
            }
        }
        return voRes;
    }
    
    void setCover(CmsExchanges e) {
        if(e.getCovers() == null || e.getCovers().size() == 0) {
            return;
        }
        e.setCover(e.getCovers().get(0).get("url"));
    }

    @Override
    public int del(String id) {
        CmsExchanges e = cmsExchangesMapper.findById(id);
        if(e != null) {
            return cmsExchangesMapper.del(id);
        }
        return 0;
    }

    @Override
    public List<CmsExchanges> getAll() {
        // TODO Auto-generated method stub
        return null;
    }
    
    @Override
    public CmsExchanges getById(String id) {
        CmsExchanges e = cmsExchangesMapper.findById(id);
        return e;
    }

    @Override
    public PageInfo<CmsExchanges> getPageByCondition(VoQueryExchanges t, int pageNum, int pageSize, String orderBy) throws XtcxException {
        User u = getUser();
        if (null == u) {
            throw new XtcxException ("登录已超时，请重新登录");
        }
        Page<CmsExchanges> page = PageHelper.startPage(pageNum, pageSize);
        if(StringUtils.isEmpty(orderBy)) {
            PageHelper.orderBy("a.create_time desc");
        }else {
            PageHelper.orderBy(orderBy);
        }
        //管理员权限不同
        /*User user = this.getUser();
        if(user.getUserType() == 0) {
            t.setPublishUserId(user.getUserId());
        }*/
        if (0 != u.getUserType() && 101 != u.getUserType()) {
            t.setPublishUserId(u.getUserId());
        }
        cmsExchangesMapper.findByCondition(t);
        PageInfo<CmsExchanges> info = new PageInfo<CmsExchanges>(page);
        CmsExchanges iVo = null;
        for (int i = 0; i < info.getList().size(); i++) {
            iVo = info.getList().get(i);
            iVo.setExStatus(getExStatus(iVo));
        }
        return info;
    }

    public String getExStatus(CmsExchanges ce)  {
        //日期判断数值大小
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        int nowDt = Integer.parseInt(sdf.format(System.currentTimeMillis()).toString());
        int getEnrollStart=Integer.parseInt(sdf.format(ce.getEnrollStart()).toString());
        int getEnrollEnd=Integer.parseInt(sdf.format(ce.getEnrollEnd()).toString());
        int getExStart=Integer.parseInt(sdf.format(ce.getExStart()).toString());
        int getExEnd=Integer.parseInt(sdf.format(ce.getExEnd()).toString());
        if (nowDt<getExStart && nowDt<getEnrollStart) {
            return "未开始";
        } else if (nowDt>=getEnrollStart && nowDt<=getEnrollEnd && nowDt<getExStart) {
            return "报名中";
        } else if (nowDt> getEnrollEnd && nowDt<getExStart) {
            return "即将开始";
        } else if (nowDt>= getExStart  && nowDt<=getEnrollEnd ) {
            return "进行中,可报名";
        } else if (nowDt>=getExStart && nowDt<=getExEnd) {
            return "进行中";
        } else if (nowDt>getExEnd) {
            return "已结束";
        }
        return "";
    }

    @Override
    public PageInfo<CmsExchangesEnroll> getEnrollPageByCondition(VoQueryExchanges t, int pageNum, int pageSize, String orderBy) {
        Page<CmsExchangesEnroll> page = PageHelper.startPage(pageNum, pageSize);
        if(StringUtils.isEmpty(orderBy)) {
//            PageHelper.orderBy("enroll_date desc");
        }else {
            PageHelper.orderBy(orderBy);
        }
        //管理员权限不同
        /*User user = this.getUser();
        if(user.getUserType() == 0) {
            t.setPublishUserId(user.getUserId());
        }*/
        ExchangeEnrollCondition eec = new ExchangeEnrollCondition();
        eec.setExId(t.getId());
        eec.setName(t.getObjName());
        eec.setEnrollStart(WzDateUtil.str2Dt(t.getEnrollStart(), WzDateUtil.DT_FMT_6));
        eec.setEnrollEnd(WzDateUtil.str2Dt(t.getEnrollEnd(), WzDateUtil.DT_FMT_6));
        cmsExchangesEnrollMapper.selectByCondition(eec);
        PageInfo<CmsExchangesEnroll> info = new PageInfo<CmsExchangesEnroll>(page);
        return info;
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(formatter.parse(""));
    }

    @Override
    public boolean check(String id) {
        CmsExchanges e = cmsExchangesMapper.findById(id);
        if(e == null || e.getCheckStatus() != 0) {
            return false;
        }
        e.setCheckStatus(1);
        User user = this.getUser();
        e.setCheckUserId(user.getUserId());
        e.setCheckDate(new Date());
        if(cmsExchangesMapper.update(e) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public VoResponse check(List<String> ids) {
        VoResponse voRes = new VoResponse();
        int count = 1;
        for(String id : ids) {
            if(!this.check(id)) {
                voRes.setFail(voRes);
                voRes.setMessage("第" + count + "条数据审核失败；");
                return voRes;
            }
            count ++;
        }
        return voRes;
    }

    @Override
    public VoResponse reject(String id, String info) {
        VoResponse voRes = new VoResponse();
        CmsExchanges e = cmsExchangesMapper.findById(id);
        if(e == null) {
            voRes.setNull(voRes);
            voRes.setMessage("数据异常");
            return voRes;
        }
        if(e.getCheckStatus() != 0) {
            voRes.setFail(voRes);
            voRes.setMessage("状态异常");
            return voRes;
        }
        User user = this.getUser();
        BusUserCheck m = new BusUserCheck();
        m.setCheckStatus(2);
        m.setChecker(user.getUserName());
        m.setInfo(info);
        m.setFormId(id);
        int result = busUserCheckMapper.insert(m);
        if(result > 0) {
            e.setCheckStatus(2);
            e.setCheckUserId(user.getUserId());
            e.setCheckDate(new Date());
            result = cmsExchangesMapper.update(e);
            if(result > 0) {
                return voRes;
            }
        }
        voRes.setFail(voRes);
        return voRes;
    }

    @Override
    public VoResponse onOrOff(String id, int val) {
        VoResponse voRes = new VoResponse();
        if(val == 0 || val == 1) {
            cmsExchangesMapper.updateReadable(id, val);
        }
        return voRes;
    }

    @Override
    public VoResponse isTop(String id, int val) {
        VoResponse voRes = new VoResponse();
        if(val >= 0) {
            cmsExchangesMapper.updateStickSort(id, val);
        }
        return voRes;
    }

    @Override
    public VoResponse taskDoingSum() {
        VoResponse voRes = new VoResponse();
        User user = getUser();
        if (null == user) {
            voRes.setFail(voRes);
            voRes.setMessage("登录已超时，请重新登录");
            return voRes;
        }
        if (0 == user.getUserType() || 101 == user.getUserType()) {
            voRes.setData(cmsExchangesMapper.taskAllDoingSum());
        } else {
            voRes.setData(cmsExchangesMapper.taskDoingSum(user.getUserId()));
        }
        return voRes;
    }

    @Override
    public VoResponse exportEnroll(VoQueryExchanges param, OutputStream out) {
        VoResponse voRes = new VoResponse();
        User u = getUser(param.getTokenStr());
        if (null == u) {
            voRes.setFail(voRes);
            voRes.setMessage("未登录或登录已超时");
            return voRes;
        }
        ExchangeEnrollCondition eec = new ExchangeEnrollCondition();
        eec.setExId(param.getId());
        List<CmsExchangesEnroll> list = cmsExchangesEnrollMapper.selectByCondition(eec);
        if (null == list || 0 == list.size()) {
            voRes.setFail(voRes);
            voRes.setMessage("此活动无人报名");
            return voRes;
        }
        ExcelUtil.writeExEnrollExcel(list, out);
        return null;
    }
}
